﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
using System.Threading;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Soap;


namespace RapGetNet
{
    public partial class AddLinks : Form
    {
        #region TestForm
        public AddLinks()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
        }


        private void lnkCnl_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void lnkOk_Click(object sender, EventArgs e)
        {
            string substring = Regex.Replace(txtLNK.Text, "http://", "");
            string substring2 = Regex.Replace(substring, "\r", "");
            string substring3 = Regex.Replace(substring2, "\n", "");
            string substring4 = Regex.Replace(substring3, " ", "");
            Regex reg = new Regex(@"rapidshare.com/files/(\d{8,})/(\w*)"); //(\s)
            Match m = reg.Match(substring4);

            if (!m.Success)
            {
                MessageBox.Show(m.Value + " není validní rapid link!");
                return;
            }

            String[] linky2 = Regex.Split(substring4, "rapidshare.com/files/");



            //String[] linky = Regex.Split(linky, "/files/");
            //string [] al = new string[linky.Length];
            List<string> al = new List<string>();
            foreach (string line in linky2)
            {
                if (!String.IsNullOrEmpty(line))
                {
                    al.Add(line);
                }
            }

            string[] linky = al.ToArray();




            listBox1.Items.AddRange(linky);
            progressBar1.Maximum = linky.Length;


            string[][] grid = new string[linky.Length][];
            for (int i = 0; i < linky.Length; i++)
            {
                grid[i] = linky[i].Split('/');
            }

            int totalCount = 0;
            foreach (string[] line in grid)
            {
                totalCount++;
                /*int m1 = int.Parse(line[3]),
                    m2 = int.Parse(line[4]),
                    m3 = int.Parse(line[5]);
                m1Total += m1;
                m2Total += m2;
                m3Total += m3;
                switch (line[1].Trim())
                {
                    case "male":
                        maleCount++;
                        m1MaleTotal += m1;
                        break;
                    case "female":
                        femaleCount++;
                        m1FemaleTotal += m1;
                        break;
                }*/
            }
            string[,] b = new string[linky.Length, 2];


            for (int k = 0; k < linky.Length; k++)
            {
                for (int l = 0; l < 1; l++)
                {
                    b[k, l] = grid[k][l];
                    //dataGridView1.Rows.Add(grid[k]);
                }
            }
            /*
            for (int k = 0; k < linky.Length; k++)
            {
                for (int l = 0; l < 2; l++)
                {
                    b[k, l] = grid[k][l];
                    dataGridView1.Rows.Add(grid[l]);
                }
            }
            */

            //dataGridView1.DataSource = new ArrayCom.Data.ArrayDataView(b);


            // int n = 3;//pocet riadkov
            // Declare the array of two elements:
            //   string[][] arr = new string[n][];

            // Initialize the elements:
            // arr[0] = new string[2] { "1231231234", "archive.rar" };
            // arr[1] = new string[2] { "1231231965", "archive2.rar" };
            //  arr[2] = new string[2] { "1231231125", "archive3.rar" };

            /*  // Display the array elements:
              for (int i = 0; i < arr.Length; i++)
              {
                  System.Console.Write("Element({0}): ", i);

                  for (int j = 0; j < arr[i].Length; j++)
                  {
                      System.Console.Write("{0}{1}", arr[i][j], j == (arr[i].Length - 1) ? "" : " ");

                  }
                  System.Console.WriteLine();
                  System.Console.ReadKey();
              }*/
            /* using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\WriteLines.txt"))
             {
             for (int i = 0; i < grid.Length; i++)
             {
                 //System.Console.Write("Element({0}): ", i);
                // System.Console.Write("Row({0}): http://rapidshare.com/files/", i);
                 file.Write("Row({0}): http://rapidshare.com/files/", i);
                 for (int j = 0; j < grid[i].Length; j++)
                 {
                    // System.Console.Write("{0}{1}", grid[i][j], j == (grid[i].Length - 1) ? "" : "/");
                     file.Write("{0}{1}", grid[i][j], j == (grid[i].Length - 1) ? "" : "/");
                 }
                // System.Console.WriteLine();
                 //System.Console.ReadKey();
             }
             }
             */
            List<string> listdetail = new List<string>();

            for (int i = 0; i < grid.Length; i++)
            {
                string fls = grid[i][0];
                string fln = grid[i][1];
                //string getVars = String.Format("sub=checkfiles_v1&files={0}&filenames={1}", grid[i][j], j == (grid[i].Length - 1)); //? "" : "");
                string getVars = "?sub=checkfiles_v1&files=" + fls + "&filenames=" + fln;
                //Initialisation, we use localhost, change if appliable
                HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format("http://api.rapidshare.com/cgi-bin/rsapi.cgi{0}", getVars));
                //This time, our method is GET.
                WebReq.Method = "GET";
                //From here on, it's all the same as above.
                HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
                //Let's show some information about the response
                Console.WriteLine(WebResp.StatusCode);
                Console.WriteLine(WebResp.Server);

                //Now, we read the response (the string), and output it.
                Stream Answer = WebResp.GetResponseStream();
                StreamReader _Answer = new StreamReader(Answer);
                string filemoredata = _Answer.ReadToEnd();

                listdetail.Add(filemoredata);
                progressBar1.Value = progressBar1.Value + 1;

            }



            //string[] serarray = listdetail.ToArray();
            //SerializeArray(serarray, "files.xml");
            //DeSerializeArray("files.xml");
            //string [] lalal = DeSerializeArray("files.xml");
            //MessageBox.Show(lalal[1]);
            //RapGet objct = new RapGet();
            //objct.InsertLinks();
            

           /* XmlSerializer serializer = new XmlSerializer(typeof(Settings));
            TextWriter tw = new StreamWriter("d:/dataasdf9.xml");
            serializer.Serialize(tw, setting);
            tw.Close();*/
            // string[] outputlist = listdetail.ToArray();
            //listBox2.Items.AddRange(outputlist);
            //RapGet robj = new RapGet();
            //robj.Hide();
            SendLinksData(listdetail);
            this.Close();


            /* string[][] detail = new string[outputlist.Length][];
             for (int i = 0; i < outputlist.Length; i++)
             {
                 detail[i] = outputlist[i].Split(',');
                 dataGridView1.Rows.Add(detail[i]);
             }*/


            /*  string[] inputarr = listdetail.ToArray();
              string[][] detail = new string[inputarr.Length][];
              for (int i = 0; i < inputarr.Length; i++)
              {
                  detail[i] = inputarr[i].Split(',');
                  // dataGridView1.Rows.Add(detail[i]);
                  MessageBox.Show("asd");
              }
              TreeGridNode node;
              string substring0 = detail[0][1];
              // string substring1 = test[1];

              //Regex reg = new Regex(@"(\d{8,})/(\w*)"); //(\s)
              Regex rege = new Regex(@"([a-zA-Z0-9\.\-]).part(\d+).rar");
              Match m1 = rege.Match(substring0);
              MessageBox.Show(substring0);
              //if (!m.Success)
              if (m1.Success)
              {
                  MessageBox.Show("regex suces");
                  int aa = substring0.IndexOf(".part");
                  //int b = substring0.IndexOf(".rar");
                  //outputHtml = binFileData.Remove(a, b - a + 1);
                  string substring1 = substring0.Remove(aa, substring0.Length - aa);

                  MessageBox.Show("validní rapid link!");
                  //return;

                  node = treeGridView2.Nodes.Add(substring1, "michael", "11/27/2005 1:02 AM");

                  for (int ab = 0; ab < detail.Length; ab++)
                  {
                      if (ab == 0)
                      {
                          node = node.Nodes.Add(detail[0][1], "tab", "10/19/2005 1:02 AM");
                      }
                      else
                      {
                          node = node.Parent.Nodes.Add(detail[ab][1], "tab", "10/19/2005 1:02 AM");
                      }
                  }
                  MessageBox.Show("end");
              }
              */

            
        }
        public void SendLinksData(List<string> datalist)
        {
            RapGet objct = new RapGet();
            objct.inputlist = datalist;
            //objct.Show();
            objct.Refresh();
            //Thread t = new Thread(new ThreadStart(objct.InsertLinks));
            //t.Start();
            objct.InsertLinks();
        }

        public static void SerializeArray(string[] arList, string fname)
        {
            // Serialize the passed in string array to a SOAP message into the specified
            // xml file.
            //Console.WriteLine(arList[0]);
            //Console.WriteLine(arList[1]);
            //Console.WriteLine("Please wait while settings are saved...");
            FileStream fstream = new FileStream(fname, FileMode.Create, FileAccess.Write);
            SoapFormatter soapFormat = new SoapFormatter();
            try
            {
                soapFormat.Serialize(fstream, arList);
            }
            finally
            {
                fstream.Close();
                //Console.WriteLine("Soap transfer is complete!");
            }
        }
       /* public static void DeSerializeArray(string fname)
        {
            // Deserialize the SOAP message back into a string array.
            FileStream fstream = new FileStream(fname, FileMode.Open, FileAccess.Read);
            SoapFormatter soapFormat = new SoapFormatter();
            string[] ba;

            try
            {
                ba = (string[])soapFormat.Deserialize(fstream);
            }
            finally
            {
                fstream.Close();
                Console.WriteLine("Soap transfer is complete!");
            }
            Console.WriteLine(ba[0]);
            Console.WriteLine(ba[1]);
            return ba;
        }*/

        public static string[] DeSerializeArray(string fname)
        {
            // Deserialize the SOAP message back into a string array.
            FileStream fstream = new FileStream(fname, FileMode.Open, FileAccess.Read);
            SoapFormatter soapFormat = new SoapFormatter();
            string[] ba;

            try
            {
                ba = (string[])soapFormat.Deserialize(fstream);
            }
            finally
            {
                fstream.Close();
                //Console.WriteLine("Soap transfer is complete!");
            }
            //Console.WriteLine(ba[0]);
            //Console.WriteLine(ba[1]);
            return ba;
        }
        #endregion

    }
}